/*
 * 查找 cocoapods specs 或 私有spec源 中指定的 spec 
 *
 * 注意 localStorage 存储方式
 *
 */
<template>
  <div class="content">
    <!-- 顶部提示区域 -->
    <el-alert
     title="指定 specs 源，快速查找对应的 spec，可以是 cooapods specs 源，或者自定义的私有源" 
     type="info"
     center
     show-icon 
     :closable="false">
    </el-alert>

    <!-- 添加源的区域 -->
    <div class='specs-area-view'>
      <el-button @click="handleAddSpecAction">添加 specs 源</el-button>
      <div class="specs-list">
        <div class="spec-item" v-for="(item, index) in specsSourcePath" :key="index">
          <span>{{ item }}</span>
          <el-button type="danger" @click="handleDeleteSpecAction(index)" plain>删除</el-button>
        </div>
      </div>
    </div>

    <!-- 输入框区域 -->
    <div class="search-view">
      <el-input 
        placeholder="请输入搜索内容" 
        prefix-icon="el-icon-search" 
        clearable
        v-model="searchSpec" 
        @change="observeInputValueChange">
      </el-input>
      <el-button 
        type="primary" 
        icon="el-icon-search" 
        :disabled="!enableClickSearch" 
        @click="handleSearchAction">
        搜索
      </el-button>
    </div>

    <!-- 搜索结果展示区域 -->
    <div class="result-view" v-show="showSearchResult">
      <el-alert 
        :title="searchResultShowText" 
        :type="resultViewAlertType" 
        show-icon 
        :closable="false">
      </el-alert>
      <button v-show="resultViewShowButton" @click="handleOpenPathAction">展示路径</button>
    </div>
  </div>
</template>

<script>
document.title = '查询 spec'

const { ipcRenderer } = window.require('electron')
const fs = window.require('fs')
const md5 = require('md5-node')
const { OPENFINDEREVENTKEY, OPENFINDEREVENTREPLYKEY, DISPLAYINFINDEREVENTKEY } = require('@/config/constText.js')

export default {
  data () {
    return {
      specsSourcePath: [],
      searchSpec: '',           /** 绑定输入框的内容 */
      showSearchResult: false,  /** 是否展示搜索结果视图 */
      isSearchSuccess: false,   /** 记录是否搜素成功 */
      searchResultShowText: ''  /** 搜索结果展示文字 */ 
    }
  },
  computed: {
    resultViewAlertType: function () {
      return this.isSearchSuccess ? 'success' : 'error'
    },
    resultViewShowButton: function () {
      return this.isSearchSuccess
    },
    enableClickSearch: function () {
      return this.specsSourcePath.length > 0 && this.searchSpec.length > 0
    }
  },
  watch: {
    specsSourcePath: function(newVal, oldVal) {
      // 本地保存一份，方便下次直接使用，注意：需要转化为 json 存取，否则会被存储为字符串
      localStorage.setItem('localSpecsSourcePathList', JSON.stringify(newVal))
    }
  },
  methods: {
    // 从本地添加 specs 源，向主进程发消息调用
    handleAddSpecAction: function() {
      ipcRenderer.send(OPENFINDEREVENTKEY, {
        properties: ['openDirectory', 'showHiddenFiles', 'dontAddToRecent']
      })
    },
    // 删除 spec
    handleDeleteSpecAction: function(idx) {
      this.specsSourcePath.splice(idx, 1)
    },
    // 监听输入框的改变
    observeInputValueChange: function (val) {
      if (!val) {
        this.showSearchResult = false
      }
    },

    // 搜索（重点）
    handleSearchAction: async function() {
      // 重置为默认状态
      this.isSearchSuccess = false
      this.showSearchResult = true
      this.searchResultShowText = '查无此 spec'

      // 通过 md5 值获取前三层的文件夹名称
      let specMd5 = md5(this.searchSpec)
      let firstLevelFolder = specMd5.substr(0,1)
      let secondLevelFolder = specMd5.substr(1,1)
      let thirdLevelFolder = specMd5.substr(2,1)
      
      for (const index in this.specsSourcePath) {
        let value = this.specsSourcePath[index]

        // 第一步：先查找自定义的源，直接拼装路径
        let _path = `${value}/${this.searchSpec}/`
        let result = await fs.existsSync(_path)
        if (result) {
          this.isSearchSuccess = true
          this.searchResultShowText = _path
          return
        }

        // 第二步：查找 Cocoapods 源，按照 md5 前 3 位值来排序，获取组合路径
        let combinatePath = `${value}/${firstLevelFolder}/${secondLevelFolder}/${thirdLevelFolder}/${this.searchSpec}/`
        result = await fs.existsSync(combinatePath)
        if (result) {
          this.isSearchSuccess = true
          this.searchResultShowText = combinatePath
          return
        }
      }
    },
    // 打开结果路径
    handleOpenPathAction: function() {
      ipcRenderer.send(DISPLAYINFINDEREVENTKEY, this.searchResultShowText)
    }
  },
  created () {
    // 监听事件通知
    ipcRenderer.on(OPENFINDEREVENTREPLYKEY, (event, filePaths) => {
      this.specsSourcePath = this.specsSourcePath.concat(filePaths)
    })
    // 本地数据赋值
    let result = localStorage.getItem('localSpecsSourcePathList')
    if (result) {
      this.specsSourcePath = JSON.parse(result)
    }
  }
};
</script>

<style lang="less" scoped>

.content {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin-top: 10px;

  .specs-area-view {
    margin: 10px 0;

    .el-button {
      margin-bottom: 10px;
    }

    .spec-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: lightgray;
      margin-bottom: 1px;

      span {
        padding-left: 6px;
      }
    }

  }

  .search-view {
    display: flex;

    .el-input {
      margin: 0 10px 0 0;
    }
  }

  .result-view {
    margin-top: 20px;
    display: flex;
    // align-items: center;

    button {
      width: 100px;
    }
  }
}

</style>